package models

import (
	"github.com/rs/xid"
)

// Supply 供应商信息
type Supply struct {
	SupplyID    string `gorm:"primary_key"`
	Name        string `gorm:"size:255;not null"`
	Tel         string
	Manager     string `gorm:"not null"`
	WeiXin      string
	QQ          string
	License     string
	BankAccount string
	Address     string
}

// CreateSupply 创建供应商
func CreateSupply(supply *Supply) error {
	supply.SupplyID = xid.New().String()

	tx := db.Begin()

	err := tx.Table("supplies").Create(supply).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

// DeleteSupply 删除供应商
func DeleteSupply(supplyID string) error {
	tx := db.Begin()
	err := tx.Table("supplies").Where("supply_id = ?", supplyID).Delete(Supply{}).Error
	if err != nil {
		tx.Rollback()
		return err
	}

	tx.Commit()
	return nil
}

// UpdateSupply 更新供应商信息
func UpdateSupply(supplyID string, newName, newTel, newManager, newAddress, newWeiXin, newQQ, newLicense, newBankAccount string) error {
	supply := Supply{
		SupplyID:    supplyID,
		Name:        newName,
		Tel:         newTel,
		Manager:     newManager,
		WeiXin:      newWeiXin,
		QQ:          newQQ,
		License:     newLicense,
		BankAccount: newBankAccount,
		Address:     newAddress,
	}
	return db.Table("supplies").Table("supplies").Where("supply_id = ?", supplyID).Updates(supply).Error
}

// ListSupplys 所有供应商
func ListSupplys() (supplys []Supply, err error) {
	err = db.Table("supplies").Table("supplies").Select("supply_id, name, tel, manager,wei_xin,qq,license,bank_account, address").Find(&supplys).Error
	return
}

// GetSupply 获取供应商信息
func GetSupply(supplyID string) *Supply {
	var supply Supply
	db.Table("supplies").Where("supply_id = ?", supplyID).Select("supply_id, name, tel, manager,wei_xin,qq,license,bank_account, address").First(&supply)
	return &supply
}

// HaveName 查询是否有此供应商
func HaveName(name string) bool {
	return !db.Table("supplies").Where("name = ?", name).First(&Supply{}).RecordNotFound()
}

// HaveSupply 查询是否有此供应商
func HaveSupply(supplyID string) bool {
	return !db.Table("supplies").Where("supply_id = ?", supplyID).First(&Supply{}).RecordNotFound()
}
